package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dao.CompanyDao;
import cd.cdyb.sms.domain.Company;
import cd.cdyb.sms.dto.MessageCarrier;
import cd.cdyb.sms.dto.expand.ExCompanyDto;
import cd.cdyb.sms.exception.BusinessException;
import cd.cdyb.sms.service.CompanyService;
import cd.cdyb.sms.service.MessageService;
import cd.cdyb.sms.service.RedisService;
import cd.cdyb.sms.utils.CacheUtils;
import cd.cdyb.sms.utils.JacksonUtilPlus;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Resource
    private RedisService redisService;

    @Resource
    private CompanyService companyService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.message_routeKey}")
    private String routeKey;

    @Override
    public void sendMessage(MessageCarrier messageCarrier) throws BusinessException {
        String companyKey = messageCarrier.getCompanyKey();
        String secret = (String) redisService.vGet(CacheUtils.CacheName.COMPANY_CERTIFICATE, companyKey);
        if (secret == null) {
            ExCompanyDto cacheCompanyByKey = companyService.getCacheCompanyByKey(companyKey);
            secret = cacheCompanyByKey.getCompanySecret();
            redisService.vPut(CacheUtils.CacheName.COMPANY_CERTIFICATE, companyKey, secret);
        }
        String companySecret = messageCarrier.getCompanySecret();
        if (!companySecret.equals(secret)){
            throw new BusinessException("身份信息错误,请检查");
        }
        //削峰,发送消息队列
        rabbitTemplate.convertAndSend(routeKey, JacksonUtilPlus.toJSon(messageCarrier));
    }

    @Override
    public void sendMessageWithParam(MessageCarrier messageCarrier) throws BusinessException {
        String companyKey = messageCarrier.getCompanyKey();
        String secret = (String) redisService.vGet(CacheUtils.CacheName.COMPANY_CERTIFICATE, companyKey);
        if (secret == null) {
            ExCompanyDto cacheCompanyByKey = companyService.getCacheCompanyByKey(companyKey);
            secret = cacheCompanyByKey.getCompanySecret();
            redisService.vPut(CacheUtils.CacheName.COMPANY_CERTIFICATE, companyKey, secret);
        }
        String companySecret = messageCarrier.getCompanySecret();
        if (!companySecret.equals(secret)){
            throw new BusinessException("身份信息错误,请检查");
        }
        List<String> params = messageCarrier.getParams();
        if (CollectionUtils.isEmpty(params)){
            throw new BusinessException("参数不能为空");
        }
        //削峰,发送消息队列
        rabbitTemplate.convertAndSend(routeKey, JacksonUtilPlus.toJSon(messageCarrier));
    }
}
